const { Menu, dialog } = require("electron");
const path = require("path");
const got = require("got").default;
const imageType = require("image-type");
const fs = require("fs");

module.exports = (srcURL) => {
  const contextMenu = Menu.buildFromTemplate([
    {
      label: "图片另存为",
      click: async () => {
        const res = await got.get(srcURL);
        const chunk = Buffer.from(res.rawBody);
        const imgtype = imageType(chunk);
        const { filePath, canceled } = await dialog.showSaveDialog({
          title: "图片另存为",
          defaultPath: path.resolve(__dirname, "../public/uploads/" + new Date().valueOf() + "." + imgtype.ext),
        });
        if (!canceled) {
          fs.writeFileSync(filePath, chunk);
          console.log(filePath);
        }
      },
    },
  ]);
  contextMenu.popup();
};
